package com.example.demo.interceptor;

import com.example.demo.common.ErrorCode;
import com.example.demo.constant.CommonConstant;
import com.example.demo.context.UserContext;
import com.example.demo.exception.BusinessException;
import com.example.demo.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@RequiredArgsConstructor
    public class Experyinterceptor implements HandlerInterceptor {
    private final JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userToken = request.getHeader("Expert-Token");
        if (!StringUtils.hasText(userToken)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        Claims claimsByToken = jwtUtils.getClaimsByToken(userToken, CommonConstant.UserType.EXPERT);
        if (ObjectUtils.isEmpty(claimsByToken)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        Object id =  claimsByToken.get("id");
        Long userId = Long.parseLong(id.toString());
        UserContext.setUserId(userId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.clear();
    }
}
